package ro.k.filters;

import java.io.IOException;

import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ro.k.servlets.KConstants;
import ro.k.servlets.LoginServlet;
import ro.k.web.beans.UserBean;

/**
 * Servlet Filter implementation class Security
 */
@WebFilter(dispatcherTypes = { DispatcherType.REQUEST, DispatcherType.FORWARD }, urlPatterns = { "*.jsp" })
public class Security implements Filter {

	private final String loginPage = "index.jsp";

	/**
	 * Default constructor.
	 */
	public Security() {
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// TODO write security filter
		HttpServletRequest hRequest = (HttpServletRequest) request;
		HttpServletResponse hResponse = (HttpServletResponse) response;
		String url = hRequest.getRequestURL().toString();	
		if (url.endsWith(loginPage) 
				|| url.contains(LoginServlet.class.getSimpleName())) {
			chain.doFilter(request, response);
		} else {
			UserBean ub = (UserBean) hRequest.getSession().getAttribute(
					KConstants.UserKey);
			if (ub == null) {
				hResponse.sendRedirect(hRequest.getContextPath() + "/"
						+ loginPage);
			} else {
				chain.doFilter(request, response);
			}
		}
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
	}

}
